<template>
	<section class="box comments">
		<h3 class="title is-5 mt-4 mb-2">评论区</h3>
		<el-divider class="mt-3"></el-divider>
		<!-- 
			提交评论的表单: 只有在登录的状态下才显示 
			每次提交一个新的评论后，都要重新再加载一次评论列表，即:
			一旦在子组件中触发了 load-comments 方法，那么都会调用一下 getCommentsByPostId
		 -->
		<comments-form 
			v-if="token"
			:post-id="postId"  
			@load-comments="getCommentsByPostId" 
		/>

		<!-- 评论列表 -->
		<comments-item 
			v-for="comment in comments" 
			:key="`comment-${comment.commentId}`" 
			:comment="comment" 
		/>
	</section>
</template>

<script>
import { mapGetters } from 'vuex'
import { fetchCommentsByPostId } from '@/api/comment'
import CommentsForm from './CommentsForm'
import CommentsItem from './CommentsItem'

export default {
  	name: 'Comments',

	components: {
		CommentsForm,
		CommentsItem
	},

	props: {
		// 从 Detail.vue 父组件传过来的 postId
		postId: {
			type: String,
			default: null
		}
	},

	data() {
		return {
			// 根据 postId 获取的评论列表
			comments: []
		}
	},
	
	computed: {
		...mapGetters([
			'token'
		])
  	},

	async mounted() {
		await this.getCommentsByPostId(this.postId)
	},

	methods: {
		// 初始化
		async getCommentsByPostId(postId) {
			fetchCommentsByPostId(postId).then(response => {
				const { data } = response
				this.comments = data
			})
		}
	}
}
</script>
